<?php

namespace App\Http\Controllers;
// use Illuminate\Http\Request;
use App\Models\GeoJson;
use App\Models\DangAn;
use Request;

class ApiController extends Controller
{
    // 添加geojson数据文件
    function add_geojson()
    {
      $gongcheng_id = request::input('gongchengid');
      $geojson_string = request::input('geojson');

      $geojson_name = $gongcheng_id . '.geojson';

      $geojson = GeoJson::where('geojson_name', $geojson_name)->first();

      if(empty($geojson))
      {
        $geojson = new GeoJson();
        $geojson->gongcheng_id = $gongcheng_id;
        $geojson->geojson_name = $geojson_name;
        $geojson->geojson = $geojson_string;
        $geojson->add_time = now();
        $geojson->save();
      } else {
        $geojson->gongcheng_id = $gongcheng_id;
        $geojson->geojson_name = $geojson_name;
        $geojson->geojson = $geojson_string;
        $geojson->add_time = now();
        $geojson->save();
      }     

      // 保存geojosn文件
      $filename = './openlayers/geojson/' . $gongcheng_id . '.geojson';
      $file = fopen($filename, 'w+');
      fwrite($file, $geojson_string);
      fclose($file);

      return 1;
    }

    // geojson文件列表
    function geojson_list()
    {
      $geojsons = GeoJson::get();
      // $geojsons = DangAn::where('id', '<', 10)->get();
      return $geojsons;
    }

    // 对应的图层的id
    function geojson_id($id)
    {
      $geojson = GeoJson::find($id);
      return $geojson;
    }

    // 档案数据列表,查询
    function dangan_list()
    {
      $key = request::input('searchkey');
      if($key == '')
      {
        $dangans= DangAn::paginate(20);
      }

      $dangans= DangAn::where('danganhao', 'like', '%'.trim($key).'%')
                        ->OrWhere('xiangmumingcheng', 'like', '%'.trim($key).'%')
                        ->OrWhere('jianshedanwei', 'like', '%'.trim($key).'%')
                        ->OrWhere('xuanzhizheng', 'like', '%'.trim($key).'%')
                        ->OrWhere('yongdizheng', 'like', '%'.trim($key).'%')
                        ->OrWhere('fanganshendingtongzhishu', 'like', '%'.trim($key).'%')
                        ->OrWhere('gongchengzheng', 'like', '%'.trim($key).'%')
                        ->OrWhere('jungongzheng', 'like', '%'.trim($key).'%')
                        ->OrWhere('tiaojianbianhao', 'like', '%'.trim($key).'%')
                        ->OrWhere('xiangcunbianhao', 'like', '%'.trim($key).'%')
                        ->paginate(20);

      return $dangans;
    }

    // 获得对应的档案号的数据
    function dangan_name()
    {
      $danganhao = request::input('danganhao');
      $dangan= DangAn::where('danganhao', $danganhao)->first();
      return $dangan;
    }
}

